package com.xuan.listener;

import com.rabbitmq.client.Channel;
import com.xuan.entity.dto.LoggingMessage;
import com.xuan.entity.po.OperationLogs;
import com.xuan.mapper.OperationLogsMapper;
import com.xuan.service.IOperationLogsService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

import static com.xuan.constants.LoggingConstants.LOGGING_QUEUE;

@Component
public class LoggingMessageListener {
    @Autowired
    private IOperationLogsService operationsService;
    @RabbitListener(queues = LOGGING_QUEUE, containerFactory = "manualAckContainerFactory")
    public void loggingMessageHandler(LoggingMessage loggingMessage, Channel channel,
                                      @Header(AmqpHeaders.DELIVERY_TAG) long tag,
                                      @Header(AmqpHeaders.CONSUMER_QUEUE) String queueName) {
        try {
            System.out.println("处理消息: " + loggingMessage + ", 来自队列：" + queueName);
            OperationLogs operationLogs = new OperationLogs();
            // 保存日志消息到数据库
            BeanUtils.copyProperties(loggingMessage, operationLogs);
            boolean save = operationsService.save(operationLogs);
            if (!save) {
                throw new RuntimeException("保存日志消息失败");
            }
            // 手动确认
            channel.basicAck(tag, false);
        } catch (IOException e) {
            try {
                // 拒绝消息并重新入队
                channel.basicNack(tag, false, true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
